package com.xh.bussiness.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xh.bussiness.course.bean.dto.CourseDto;
import com.xh.bussiness.permission.model.School;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.bean.dto.StudentDto;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.system.service.ISchoolService;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.tms.bean.request.ClassRequest;
import com.xh.bussiness.tms.bean.request.ClassStudentRequest;
import com.xh.bussiness.tms.dao.ClassMapper;
import com.xh.bussiness.tms.model.ClassStudent;
import com.xh.bussiness.tms.service.IClassManageService;
import com.xh.bussiness.tms.service.IClassStudentService;
import com.xh.core.bean.XhPage;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.bussiness.tms.model.Class;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import jdk.internal.dynalink.support.ClassMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;

@Service
public class ClassManageServiceImpl extends BaseServiceImpl<ClassMapper, Class> implements IClassManageService {

    @Autowired
    private IDictionaryService dictionaryService;
    @Autowired
    private IClassStudentService classStudentService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ISchoolService schoolService;

    @Override
    public XhPage<Class> queryByPage(XhPage page, ClassRequest bean) {
//        bean.setTeacherId(UserUtils.getCurrentUserId());
        XhPage<Class> result = this.dao.queryPage(page, bean);
        List<School> schools = schoolService.queryAll();
        List<Class> list = result.getRecords();
        for (Class aClass : list) {
            String subject = aClass.getSubjectId();
            String gradeId = aClass.getGradeId();
            String courseTypeId = aClass.getClassTypeId();

            Dictionary subjectDic = dictionaryService.queryByCode(subject, "SUBJECT");
            if (subjectDic != null) {
                aClass.setSubjectName(subjectDic.getName());
            }
            Dictionary gradeDic = dictionaryService.getById(gradeId);
            if (gradeDic != null) {
                aClass.setGradeName(gradeDic.getName());
            }

            Dictionary courseTypeDic = dictionaryService.getById(courseTypeId);
            if (courseTypeDic != null) {
                aClass.setClassTypeName(courseTypeDic.getName());
            }

            if(aClass.getId() != null){
                QueryWrapper<ClassStudent> qw = new QueryWrapper<>();
                qw.eq("class_id",aClass.getId());
                Integer studentCount = classStudentService.selectCount(qw);
                aClass.setStudentCount(studentCount);
            }

            String orgId = aClass.getOrgId();
            if(StringUtils.isNotEmpty(orgId)){
                for (School school : schools) {
                    if (orgId.equals(school.getId())) {
                        aClass.setOrgName(school.getSchoolName());
                        break;
                    }
                }
            }
        }

        return result;
    }

    @Override
    public boolean addStudents(ClassStudentRequest classStudentRequest) {
        if (StringUtils.isEmpty(classStudentRequest.getClassId()) || CollectionUtils.isEmpty(classStudentRequest.getStudentIds())) {
            return false;
        }
        //删除学生
        ClassStudent classStudentReq = new ClassStudent();
        classStudentReq.setClassId(classStudentRequest.getClassId());
        classStudentService.deleteStudentOrClassByClassIdOrStuId(classStudentReq);

        for (String studentId : classStudentRequest.getStudentIds()) {
            ClassStudent classStudent = new ClassStudent();
            classStudent.setClassId(classStudentRequest.getClassId());
            classStudent.setStudentId(studentId);
            classStudentService.insert(classStudent);

            Student student = new Student();
            student.setGroupStatus(1);
            student.setId(studentId);
            studentService.update(student);
        }
        Class clazz = this.getById(classStudentRequest.getClassId());
        if (!CollectionUtils.isEmpty(classStudentRequest.getStudentIds())) {
            clazz.setIsOpen(1);
        }else{
            clazz.setIsOpen(0);
        }
        this.update(clazz);
        return true;
    }

    @Override
    public List<Class> queryClassByTeacherId(String teacherId,String subjectId) {
        if (StringUtils.isEmpty(teacherId)) {
            return new ArrayList<>();
        }
        QueryWrapper<Class> qw = new QueryWrapper<>();
        qw.eq("teacher_id", teacherId);
        qw.eq("is_open", 1);
        if (!StringUtils.isEmpty(subjectId)) {
            qw.eq("subject_id", subjectId);
        }
        qw.orderByDesc("create_time");
        List<Class> classes = this.dao.selectList(qw);
        for (Class aClass : classes) {
            QueryWrapper<ClassStudent> csQw = new QueryWrapper<>();
            //csQw.eq("class_id", aClass.getThirdId());
            List<ClassStudent> students = classStudentService.queryByCondition(csQw);
            aClass.setStudentCount(students.size());
        }
        return classes;
    }

    @Override
    public List<Class> queryClassByIds(List<String> ids) {
        QueryWrapper<Class> qw = new QueryWrapper<>();
        qw.in("id", ids);
        return this.dao.selectList(qw);
    }

    @Override
    public void saveOrUpdate(Class cls) {
        Class exist = super.getById(cls.getId());
        if(exist == null){
            super.insert(cls);
        }else{
            super.update(cls);
        }
    }

    @Override
    public XhPage<StudentDto> queryStudentsByClassId(XhPage page, String classId, String name) {
        return this.getDao().queryStudentByClassId(page, classId, name);
    }

    @Override
    public Class queryClassByThridId(String thirdId, String source) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("third_id", thirdId);
        if (StringUtils.isNotEmpty(source)) {
            qw.eq("source", source);
        }
        return this.selectFirst(qw);
    }
}
